package com.kgc.bigdata.spark.streaming

import org.apache.spark.SparkConf
import org.apache.spark.streaming._

/**
  * 使用mapWithState算子实现有状态的统计分析
  */
object StatefulWordCountMapWithState {

  def main(args: Array[String]) {

    val sparkConf = new SparkConf
    sparkConf.setAppName("StatefulWordCount").setMaster("local[2]")
    val ssc = new StreamingContext(sparkConf, Seconds(5))

    ssc.checkpoint(".")

    val lines = ssc.socketTextStream("localhost", 6789)
    val words = lines.flatMap(_.split(" ")).map((_, 1))

    val mappingFunc = (word: String, value: Option[Int], state: State[Int]) => {
      val sum = value.getOrElse(0) + state.getOption.getOrElse(0)
      state.update(sum)
      (word, sum)
    }
    val result = words.mapWithState(StateSpec.function(mappingFunc))

    result.print()
    ssc.start()
    ssc.awaitTermination()
  }
}
